package org.i_plus.model.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class GenericDAOImp<T> implements GenericDAO<T> {
    
	private SessionFactory sessionFactory = null;
	
	public void setSessionFactory(SessionFactory sessionFactory){
		this.sessionFactory = sessionFactory;
	}

	
	@Override
	public void save(T entity) {
		Session session = sessionFactory.getCurrentSession();
		session.save(entity);
	}

	@Override
	public void update(T entity) {
		Session session = sessionFactory.getCurrentSession();
		session.saveOrUpdate(entity);
	}

	@Override
	public void deleteByString(Class clazz,String pk) {
		Session session = sessionFactory.getCurrentSession();
		T t = null;
		t = (T) session.get(clazz, pk);
		session.delete(t);
	}
	@Override
	public void deleteByInt(Class clazz,int pk) {
		Session session = sessionFactory.getCurrentSession();
		T t = null;
		t = (T) session.get(clazz, pk);
		session.delete(t);
	}

	@Override
	public List<T> findMany(Query query) {
		List<T> t;
        t = (List<T>) query.list();
       
        return t;
	}

	@Override
	public T findOne(Query query) {
		 T t;
	      t = (T) query.uniqueResult();
	      return t;
	}

	@Override
	public List<T> findAll(Class clazz) {
		Session session = sessionFactory.getCurrentSession();
	        List T = null;
	        Query query = session.createQuery("from " + clazz.getName());
	        T = query.list();
	        return T;
	}

	@Override
	public T findByPKInt(Class clazz,int pk) {
		Session session = sessionFactory.getCurrentSession();
	        T t = null;
	        t = (T) session.get(clazz, pk);
	        return t;
	}
	@Override
	public T findByPKString(Class clazz,String pk) {
		Session session = sessionFactory.getCurrentSession();
	        T t = null;
	        t = (T) session.get(clazz, pk);
	        return t;
	}

}
